package com.sky.sky_common.exception;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.sky.sky_common.constant.MessageConstant;
import com.sky.sky_common.result.Result;

import io.jsonwebtoken.JwtException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(JwtException.class)
    public ResponseEntity<?> handleJwt(JwtException ex){
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of(
            "code" , "401",
            "message" , "hello, invalid or expired token, please login again"
        ));
    }

    @ExceptionHandler(EmployeeLoginException.class)
    public ResponseEntity<?> handleEmployeeLogin(EmployeeLoginException ex){
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of(
            "code" , "401",
            "message" , "userneme or password error, please check again"
        ));
    }

    @ExceptionHandler(UserLoginException.class)
    public ResponseEntity<?> handleUserLogin(UserLoginException ex){
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of(
            "code" , "401",
            "message" , "openid or openid error, please check openid"
        ));
    }

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<?> handleRuntimeException(RuntimeException ex){
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of(
            "code" , "500",
            "message" , ex.getMessage()
        ));
    }

    /**
     * 用户名username不能重复，数据库唯一约束异常
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result handleIntegrity(SQLIntegrityConstraintViolationException ex){
        // Duplicate entry 'xxx' for key 'xxx'
        String msg = ex.getMessage();
        if(msg.contains("Duplicate entry")){
            String[] split = msg.split("'");
            String username = split[1];
            return Result.error(username + MessageConstant.ALREAD_EXIST);
        }
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }
}
